package com.community.common.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.community.common.mapper.*;
import com.community.common.pojo.Constant;
import com.community.common.pojo.PageRequest;
import com.community.common.pojo.domain.*;
import com.community.common.pojo.dto.ManageUserCondition;
import com.community.common.pojo.response.CodeEnum;
import com.community.common.pojo.response.MyResponse;
import com.community.common.pojo.vo.ManagerUserVo;
import com.community.common.util.CommonUtil;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 小区管理员表 服务实现类
 * </p>
 *
 * @author superman
 * @since 2020-08-02
 */
@Slf4j
@Service
public class ManagerUserService extends ServiceImpl<ManagerUserMapper, ManagerUser> {

    @Resource
    private ManagerUserMapper managerUserMapper;
    @Resource
    private UserPermissionMapper userPermissionMapper;
    @Resource
    private PublicUserMapper publicUserMapper;
    @Resource
    private CameraService cameraService;
    @Resource
    private OwnerHouseMapper ownerHouseMapper;
    @Resource
    private OwnerFriendMapper ownerFriendMapper;

    public MyResponse add(ManagerUser managerUser) {
        managerUser.setId(String.valueOf(CommonUtil.getId()));
        managerUser.setRole(1);
        managerUser.setCreateTime(LocalDateTime.now());
        managerUser.setUpdateTime(LocalDateTime.now());
        int insert = managerUserMapper.insert(managerUser);
        if (insert == 1) {
            return MyResponse.success();
        }
        return MyResponse.fail();
    }

    public boolean edit(ManagerUser managerUser) {
        managerUser.setUpdateTime(LocalDateTime.now());
        int i = managerUserMapper.updateById(managerUser);
        return true;
    }

    public boolean delete(List<Long> ids) {
        if (ids != null && ids.size() > 0) {
            for (Long id : ids) {
                managerUserMapper.deleteById(id);
                return true;
            }
        }
        return false;
    }

    public String getCommunityIdFromSession(HttpSession session) {
        String role = (String) session.getAttribute("role");
        String communityId = null;
        if (StringUtils.equals(role, "1")) {
            communityId = (String) session.getAttribute("communityId");
        }
        return communityId;
    }

    public List<ManagerUserVo> queryByPage(PageRequest<ManageUserCondition> pageRequest) {
        ManageUserCondition condition = pageRequest.getCondition();
        PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());
        return managerUserMapper.queryByPage(condition);
    }

    //timeType 0-不允许 1-1天 2-1月 3-半年 4-1年 5-10年
    public MyResponse cameraAuthorization(String id, Integer userType,
                                          String timeType, String communityId) {
        PublicUser publicUser = publicUserMapper.selectById(id);
        if (publicUser == null) {
            return MyResponse.fail(CodeEnum.NOT_FOUND);
        }
        List<Camera> cameras = cameraService.getByCommunityId(communityId);
        List<String> cameraIds = cameras.stream().map(Camera::getId).collect(Collectors.toList());
        LocalDateTime now = LocalDateTime.now();
        int currentAllow = 0;
        int targetAllow = 1;
        LocalDateTime endTime;
        try {
            switch (timeType) {
                //1天
                case Constant.TIME_TYPE_ONE_DAY:
                    endTime = now.plusDays(1);
                    break;
                //1月
                case Constant.TIME_TYPE_ONE_WEEK:
                    endTime = now.plusMonths(1);
                    break;
                //半年
                case Constant.TIME_TYPE_HALF_YEAR:
                    endTime = now.plusMonths(6);
                    break;
                //1年
                case Constant.TIME_TYPE_ONE_YEAR:
                    endTime = now.plusYears(1);
                    break;
                //10年
                case Constant.TIME_TYPE_TEN_YEAR:
                    endTime = now.plusYears(10);
                    break;
                //默认 删除权限 如果传入参数不是指定范围内的参数 会删除权限
                default:
                    currentAllow = 1;
                    targetAllow = 0;
                    endTime = now;
            }
            //设置当前小区下面所有相机的权限
            for (String cameraId : cameraIds) {
                LambdaQueryWrapper<UserPermission> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(UserPermission::getRelevanceId, id);
                queryWrapper.eq(UserPermission::getCameraId, cameraId);
                UserPermission userPermission = userPermissionMapper.selectOne(queryWrapper);
                if (userPermission == null) {
                    UserPermission build = UserPermission.builder()
                            .id(CommonUtil.getIdStr())
                            .relevanceId(id)
                            .idTable(userType)
                            .cameraId(cameraId)
                            .communityId(communityId)
                            .currentAllow(currentAllow)
                            .targetAllow(targetAllow)
                            .commandStatus(Constant.COMMAND_INIT)
                            .startTime(now)
                            .endTime(endTime)
                            .createTime(now)
                            .updateTime(now)
                            .build();
                    userPermissionMapper.insert(build);
                } else {
                    userPermission.setCurrentAllow(currentAllow)
                            .setTargetAllow(targetAllow)
                            .setCommandStatus(Constant.COMMAND_INIT)
                            .setStartTime(now)
                            .setCommunityId(communityId)
                            .setEndTime(endTime)
                            .setUpdateTime(now);
                    userPermissionMapper.updateById(userPermission);
                }
            }
            //更新好友的权限
            LambdaQueryWrapper<OwnerFriend> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OwnerFriend::getOpenId, publicUser.getOpenId());
            List<OwnerFriend> ownerFriends = ownerFriendMapper.selectList(wrapper);
            for (OwnerFriend ownerFriend : ownerFriends) {
                for (String cameraId : cameraIds) {
                    LambdaQueryWrapper<UserPermission> wrapper1 = new LambdaQueryWrapper<>();
                    wrapper1.eq(UserPermission::getRelevanceId, ownerFriend.getId()).eq(UserPermission::getCameraId, cameraId);
                    UserPermission userPermission1 = userPermissionMapper.selectOne(wrapper1);
                    if (userPermission1 == null) {
                        UserPermission userPermission = UserPermission.builder()
                                .relevanceId(ownerFriend.getId())
                                .idTable(1)
                                .communityId(String.valueOf(communityId))
                                .cameraId(cameraId)
                                .communityId(communityId)
                                .currentAllow(0)
                                .targetAllow(1)
                                .commandStatus(Constant.COMMAND_INIT)
                                .startTime(LocalDateTime.now())
                                .endTime(LocalDateTime.now().plusYears(15))
                                .createTime(LocalDateTime.now())
                                .updateTime(LocalDateTime.now())
                                .build();
                        userPermissionMapper.insert(userPermission);
                    } else {
                        userPermission1.setCurrentAllow(0).setTargetAllow(1).setCommandStatus(Constant.COMMAND_INIT)
                                .setStartTime(LocalDateTime.now()).setEndTime(LocalDateTime.now().plusYears(15))
                                .setUpdateTime(LocalDateTime.now()).setCommunityId(communityId);
                        userPermissionMapper.updateById(userPermission1);
                    }
                }
            }
            return MyResponse.success();
        } catch (Exception e) {
            log.error(" cameraAuthorization error ", e);
        }
        return MyResponse.fail(CodeEnum.SERVICE_EXCEPTION);
    }

    public MyResponse identityAuth(String id, Integer checkState) {
        OwnerHouse ownerHouse = ownerHouseMapper.selectById(id);
        if (ownerHouse == null) {
            return MyResponse.fail(CodeEnum.NOT_FOUND);
        }
        ownerHouseMapper.updateCheckState(id, checkState);
        return MyResponse.success();
    }

    public void updatePermission(String relevanceId, Integer targetAllow, String communityId, LocalDateTime startTime, LocalDateTime endTime) {
        LambdaQueryWrapper<UserPermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPermission::getRelevanceId, relevanceId);
        List<UserPermission> userPermissionList = userPermissionMapper.selectList(queryWrapper);
        for (UserPermission userPermission : userPermissionList) {
            if (targetAllow == 0 && userPermission != null && userPermission.getCurrentAllow() == 1 && userPermission.getCommandStatus().equals(Constant.COMMAND_SUCCESS)) {
                userPermission.setTargetAllow(0)
                        .setCommandStatus(Constant.COMMAND_INIT)
                        .setUpdateTime(LocalDateTime.now());
            } else if (targetAllow == 1) {
//            if (userPermission == null) {
//                UserPermission build = CommonUtil.buildUserPermission(relevanceId, communityId)
//                        .setTargetAllow(1)
//                        .setStartTime(startTime)
//                        .setEndTime(endTime);
//                userPermissionMapper.insert(build);
//            } else {
//                userPermission
//                        .setTargetAllow(1)
//                        .setStartTime(startTime)
//                        .setEndTime(endTime)
//                        .setUpdateTime(LocalDateTime.now());
//                userPermissionMapper.updateById(userPermission);
//            }
            }
        }

    }

}
